/**
 * UserServiceImpl.java 1.0 2007-4-21 上午03:00:27,创建 by yangfan
 */


package org.in4j.bbs.service.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.in4j.bbs.model.User;
import org.in4j.bbs.service.UserService;
import org.in4j.core.dao.AbstractHibernateDao;
import org.in4j.core.dao.support.Pagination;

/**
 *
 * @author yangfan
 * @version 1.0 2007-4-21 上午03:00:27,创建
 */
public class UserServiceImpl extends AbstractHibernateDao<User> implements UserService
{
	public int getUserCount()
	{
//		1.靠,这个方式真落后...
//		List<Long> countList = getHibernateTemplate().find();
//		int count = countList.get(0).intValue();
//		return count;
//		2.
//		return (Integer)createQuery("select count(*) from User").uniqueResult();
//		3.GenericType
		Long userCount = uniqueResult("select count(*) from User");
		return userCount.intValue();
	}

	public Pagination<User> getUserBetweenAge(int minAge,int maxAge)
	{
		DetachedCriteria criteria = createDetachedCriteria();
		criteria.add(Property.forName("age").between(minAge, maxAge));
		return findPageByCriteria(criteria);
	}

	public void saveTest()
	{
		System.out.println("\n-------------use hibernate------------\n");
		uniqueResult("select count(*) from User");
		System.out.println("\n-------------use jdbc Template------------\n");
		getJdbcTemplate().queryForInt("select count(*) from bbs_users");
		System.out.println("\n-------------after use jdbc Template------------\n");
	}

	public User getUserByName(String username)
	{
		List<User> users = find("from User u where u.name=?", username);
		if(!users.isEmpty())
			return users.iterator().next();
		return null;
	}

	@Override
	public void create(User user)
	{
		final String encryptedPassword = encryptPassword(user.getPassword());
		user.setPassword(encryptedPassword);
		super.create(user);
	}

	public User getUserByNameAndPassword(String username, String password)
	{
		final String encryptedPassword = encryptPassword(password);
		final String sql = "from User where name=? and password=?";
		List<User> users = super.find(sql, new Object[] {username,encryptedPassword});
		if(users.isEmpty())
			return null;
		return users.iterator().next();
	}

	private String encryptPassword(String password)
	{
		return password;
	}
}
